package com.mengyan.oj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mengyan.oj.common.BaseResponse;
import com.mengyan.oj.common.ErrorCode;
import com.mengyan.oj.common.ResultUtils;
import com.mengyan.oj.exception.BusinessException;
import com.mengyan.oj.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.mengyan.oj.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.mengyan.oj.model.entity.QuestionSubmit;
import com.mengyan.oj.model.entity.User;
import com.mengyan.oj.model.vo.QuestionSubmitVO;
import com.mengyan.oj.service.QuestionSubmitService;
import com.mengyan.oj.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/question_submit")
@Slf4j
public class QuestionSubmitController {

    @Resource
    private QuestionSubmitService questionSubmitService;

    @Resource
    private UserService userService;

    /**
     * 提交题目
     * @param questionSubmitAddRequest
     * @param request
     * @return
     */
    @PostMapping("/")
    public BaseResponse<Long> doQuestionSubmit(@RequestBody  QuestionSubmitAddRequest questionSubmitAddRequest, HttpServletRequest request) {

        if (questionSubmitAddRequest == null || questionSubmitAddRequest.getQuestionId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        final User loginUser = userService.getLoginUser(request);

        return ResultUtils.success(questionSubmitService.doQuestionSubmit(questionSubmitAddRequest, loginUser));
    }

    /**
     * 分页获取题目提交列表(除了管理员外,普通用户只能看到除答案 提交代码外的公开信息)
     * @param questionSubmitQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<QuestionSubmitVO>> listQuestionSubmitByPage(@RequestBody QuestionSubmitQueryRequest questionSubmitQueryRequest,
                                                                         HttpServletRequest request) {
        long current = questionSubmitQueryRequest.getCurrent();
        long pageSize = questionSubmitQueryRequest.getPageSize();
        // 从数据库中拿到原始信息
        Page<QuestionSubmit> questionSubmitPage = questionSubmitService.page(new Page<>(current, pageSize),
                questionSubmitService.getQueryWrapper(questionSubmitQueryRequest));
        // 返回脱敏信息
        User loginUser = userService.getLoginUser(request);
        return ResultUtils.success(questionSubmitService.getQuestionSubmitVOPage(questionSubmitPage, loginUser));
    }
}
